//
//  SignUpViewController.m
//  iBaby365v2
//
//  Created by Kirinrin on 14-6-6.
//  Copyright (c) 2014年 suplus. All rights reserved.
//

#import "SignUpViewController.h"
#import "NetworkAccessManager.h"
#import "UIAlertView+Kirinrin.h"
#import "PopupPickerView.h"
#import "UtilHelper.h"

#define kVerifyTimeout  60
#define kKeyboardOffset     10
#define kSaveKeyPhoneNumber @"phoneNumber"


@interface SignUpViewController ()
@property (weak, nonatomic) IBOutlet UITextField *phoneNumber;
@property (weak, nonatomic) IBOutlet UITextField *verifyCode;
@property (weak, nonatomic) IBOutlet UITextField *password;
@property (weak, nonatomic) IBOutlet UITextField *repeatPassword;
@property (weak, nonatomic) IBOutlet UITextField *childCode;

@property (weak, nonatomic) IBOutlet UIButton *getSMSVerifyCodeButton;
@property (weak, nonatomic) IBOutlet UILabel *getSMSVerifyCodeButtonTimeCount;

@property (weak, nonatomic) IBOutlet UILabel *parentTitle;
@property (assign, nonatomic) NSUInteger parentTitleCode;


@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *activityIndicator;

@property (strong, nonatomic)NSTimer *verifyButtonTimer;

@property (strong, nonatomic)PopupPickerView *pickerView;

@end

@implementation SignUpViewController{
    CGRect _keyboardRect;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    NSLog(@"viewDidLoad");
    [super viewDidLoad];
    self.parentTitleCode = 0;
    // Do any additional setup after loading the view.
    [self.getSMSVerifyCodeButtonTimeCount setText:[@(kVerifyTimeout)stringValue]];
    
    UIToolbar* numberToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
    numberToolbar.barStyle = UIBarStyleDefault;
    numberToolbar.items = [NSArray arrayWithObjects:
                           [[UIBarButtonItem alloc]initWithTitle:NSLocalizedString(@"关闭", nil) style:UIBarButtonItemStyleBordered target:self action:@selector(cancelNumberPad)],
                           [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                           [[UIBarButtonItem alloc]initWithTitle:NSLocalizedString(@"下一个", nil) style:UIBarButtonItemStyleDone target:self action:@selector(doneWithNumberPad)],
                           nil];
    [numberToolbar sizeToFit];
    self.phoneNumber.inputAccessoryView = numberToolbar;
    
    self.verifyCode.inputAccessoryView = numberToolbar;
    
    self.childCode.inputAccessoryView = numberToolbar;
}

- (void)didReceiveMemoryWarning
{
    NSLog(@"didReceiveMemoryWarning");
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
    
    [self.verifyButtonTimer invalidate];
    _verifyButtonTimer = nil;
}

-(void)viewWillAppear:(BOOL)animated{
    NSLog(@"viewWillAppear");
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

-(void)viewWillDisappear:(BOOL)animated{
    //TODO: check 计时器在界面转换时是否正确
    NSLog(@"viewWillDisappear");
    if ([self.verifyButtonTimer isValid]) {
        NSLog(@"stop the timer");
        [self.verifyButtonTimer setFireDate:[NSDate distantFuture]];
    }
    
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

#pragma mark - fix number pad next key handle keyboard next key
-(void)cancelNumberPad{
    [self.view endEditing:YES];
}

-(void)doneWithNumberPad{
    if ([self.phoneNumber isFirstResponder]) {
        [self.verifyCode becomeFirstResponder];
    }else if ([self.verifyCode isFirstResponder]){
        [self.password becomeFirstResponder];
    }else if ([self.childCode isFirstResponder]){
        [self.childCode resignFirstResponder];
        //show title choice option
        [self showPickerView:nil];
    }
    
//    [self.phoneNumber resignFirstResponder];
}
#pragma mark - keyboard show & hide handle
-(void)keyboardWasShown:(NSNotification *)notification{
    NSLog(@"keyboardWasShown");
    [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey]getValue:&_keyboardRect];
//    _keyboardSize = ([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortrait || [[UIDevice currentDevice] orientation] == UIDeviceOrientationPortraitUpsideDown) ?keyboardEndFrame.size.height : keyboardEndFrame.size.width;
    
    //find the first responser and move it up
    if ([self.repeatPassword isFirstResponder]) {
        [self moveViewToVisialbe:self.repeatPassword keyboardSize:_keyboardRect];
    }else if([self.childCode isFirstResponder]){
        [self moveViewToVisialbe:self.childCode keyboardSize:_keyboardRect];
    }

}

- (void)keyboardWillHide:(NSNotification *)notification{
    NSLog(@"keyboardWillHide");
    
//    NSTimeInterval animationDuration=0.30f;
    [UIView animateWithDuration:0.30f animations: ^{
        float width = self.view.frame.size.width;
        float height = self.view.frame.size.height;
        //上移30个单位，按实际情况设置
        CGRect rect=CGRectMake(0.0f,0.0f,width,height);
        self.view.frame=rect;
    }completion:nil];
}

// 检查位置判断是否需要移动，移动
- (void)moveViewToVisialbe:(UIView *)view keyboardSize:(CGRect )keyboardRect{
    CGFloat temp = view.superview.frame.origin.y;
    temp += view.frame.size.height;
    temp += kKeyboardOffset;
    if (temp > keyboardRect.origin.y) {
        CGFloat offsetY = keyboardRect.origin.y - temp;
        [UIView animateWithDuration:0.30f animations: ^{
            CGRect viewFrame = self.view.frame;
            CGRect endFrame = CGRectMake(0, offsetY, viewFrame.size.width, viewFrame.size.height);
            
            self.view.frame=endFrame;
        }];
    }
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (IBAction)backToUpAction:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)doSingUpAction:(id)sender {
    [self.view endEditing:YES];
    if (self.pickerView) {
        [self.pickerView removeFromSuperview];
    }
    if ([self checkForm]) {
        self.view.userInteractionEnabled = NO;
        [self.activityIndicator startAnimating];
        
        NSString *uri = @"Account/0/signUp.json";
        NSDictionary *parameter = @{@"phoneNumeber": self.phoneNumber.text, @"verifyCode":self.verifyCode.text, @"password":[UtilHelper md5LowCase:self.password.text], @"childCode": self.childCode.text, @"title": @(self.parentTitleCode)};
        [[NetworkAccessManager shareManager]POST:uri parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"opernation = %@ /nresponseOject = %@", operation, responseObject);
            int resultCode = [responseObject[@"result"]intValue];
            if (resultCode == 0) {
                //show success goto back;
                [UIAlertView alertWithMessage:@"注册成功，请登录"];
                [self dismissViewControllerAnimated:YES completion:nil];
                
            }else{
                [UIAlertView alertWithRemoteError:resultCode];
            }
            
            self.view.userInteractionEnabled = YES;
            [self.activityIndicator stopAnimating];
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [UIAlertView alertWithNetworkError];
            self.view.userInteractionEnabled = YES;
            [self.activityIndicator stopAnimating];
        }];
    }
   
}

- (IBAction)doGetSMSVerifyCode:(id)sender {
    [self.getSMSVerifyCodeButton setEnabled:NO];
    
    if ([UtilHelper isValidateMobile:self.phoneNumber.text]) {
        NSString *uriString = [NSString stringWithFormat:@"VerifyCode.sms"];
        NSDictionary *parameter = @{@"phoneNumber": self.phoneNumber.text};
        [[NetworkAccessManager shareManager]GET:uriString parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"opernation = %@\n response = %@", operation, responseObject);
            int resultCode = [responseObject[@"result"]intValue];
            if (resultCode == 0) {
                NSLog(@"验证短信已经成功发送");
                [self disableGetSMSVerifyCodeButton:nil];
            }else{
                [UIAlertView alertWithRemoteError:resultCode];
            }
            
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"network access faild \nError = %@ \nOpernation= %@", error, operation);
            [UIAlertView alertWithNetworkError];
            [self.getSMSVerifyCodeButton setEnabled:YES];
        }];
    }else{
        [UIAlertView alertWithMessage:NSLocalizedString(@"您输入的手机号码有误，请重新输入。", nil)];
    }
    
}

#pragma mark - UITextFieldDelegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == self.password) {
        //[textField resignFirstResponder];
        [self.repeatPassword becomeFirstResponder];
    }
    else if (textField == self.repeatPassword) {
        //[textField resignFirstResponder];
        [self.childCode becomeFirstResponder];
    }
    return YES;
}
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    /*
    CGRect textFieldFrame = textField.superview.frame;
    CGFloat textFieldBottomY = textFieldFrame.origin.y+textFieldFrame.size.height;
    
    CGFloat visiableViewHeight = SCREEN_HEIGHT - keyboardHeight - kKeyboardOffset;
    if (textFieldBottomY >= visiableViewHeight) {
        [UIView animateWithDuration:0.30f animations: ^{
            CGRect viewFrame = self.view.frame;
            CGRect newViewRect = CGRectMake(viewFrame.origin.x, visiableViewHeight, viewFrame.size.width, viewFrame.size.height);
            
            self.view.frame=newViewRect;
        }completion:nil];
    }
    */
    return YES;
}
/*
- (void)textFieldDidEndEditing:(UITextField *)textField{
}
 */

#pragma mark - PopupPickerView

- (IBAction)showPickerView:(id)sender {
    if (!self.pickerView) {
        self.pickerView = [[PopupPickerView alloc]initWithPickerDataSource:self pickerDelegate:self];
    }
    
    [self.pickerView showPickerView:self.view];
    
}


- (BOOL)checkForm{
    if (![UtilHelper isValidateMobile:self.phoneNumber.text]) {
        [UIAlertView alertWithFormCheckError:FCErrorInvaildPhoneNumber];
        [self.phoneNumber becomeFirstResponder];
        return NO;
    }else if (!(self.verifyCode.text.length ==4)){
        [UIAlertView alertWithFormCheckError:FCErrorInvaildLength];
        [self.verifyCode becomeFirstResponder];
        return NO;
    }else if (![UtilHelper checkPasswordValidate:self.password.text repeatPassword:self.repeatPassword.text maxlength:16]){
        [UIAlertView alertWithFormCheckError:FCErrorInvaildPassword];
        [self.password becomeFirstResponder];
        return NO;
    }else if (!(self.childCode.text.length == 15)){
        [UIAlertView alertWithFormCheckError:FCErrorInvaildLength];
        [self.childCode becomeFirstResponder];
        return NO;
    }
    
    return YES;
}


#pragma mark - about SMSVeriftyCodeButton enable and disable
- (void)updateGetSMSVerifyCodeButtonCount:(NSTimer *)timer{
    NSLog(@"updateGetSMSVerifyCodeButtonCount %@", timer.userInfo);
    int count = [[timer.userInfo objectForKey:@"count"]intValue];
    count --;
    [timer.userInfo setObject:@(count) forKey:@"count"];
    
    if (count == 0) {
        [self enableGetSMSVerifyCodeButton:nil];
    }else{
        [self.getSMSVerifyCodeButtonTimeCount setText:[@(count)stringValue]];
    }
    
}

- (void)disableGetSMSVerifyCodeButton:(id)sender{
    NSLog(@"call disableGetSMSVerifyCodeButton");
    
    NSMutableDictionary *count = [NSMutableDictionary dictionaryWithObject: @(kVerifyTimeout) forKey:@"count"];
    
    [self.getSMSVerifyCodeButton setEnabled:NO];
    [self.getSMSVerifyCodeButtonTimeCount setHidden:NO];
    
    self.verifyButtonTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateGetSMSVerifyCodeButtonCount:) userInfo:count repeats:YES];
}
- (void)enableGetSMSVerifyCodeButton:(id)sender{
    NSLog(@"call enableGetSMSVerifyCodeButton");
    self.getSMSVerifyCodeButton.enabled = YES;
    [self.getSMSVerifyCodeButtonTimeCount setText:[@(kVerifyTimeout)stringValue]];
    [self.getSMSVerifyCodeButtonTimeCount setHidden:YES];
    [self.verifyButtonTimer invalidate];
    _verifyButtonTimer = nil;
}


#pragma mark - UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    
    return 2;
}
#pragma mark - UIPickerViewDelegate
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    if (row == 0) {
        return @"孩子的妈妈";
    }else{
        return @"孩子的爸爸";
    }
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    self.parentTitleCode = row;
    if (row == 0) {
        [self.parentTitle setText:@"孩子的妈妈" ];
    }else{
        [self.parentTitle setText: @"孩子的爸爸" ];
    }
}

#pragma mark - ViewController state save and load
-(void)encodeRestorableStateWithCoder:(NSCoder *)coder{
    NSLog(@"encodeRestorableStateWithCoder");
    [coder encodeObject:self.phoneNumber.text forKey: kSaveKeyPhoneNumber];
}

-(void)decodeRestorableStateWithCoder:(NSCoder *)coder{
    NSLog(@"decodeRestorableStateWithCoder");
    self.phoneNumber.text = [coder decodeObjectForKey:kSaveKeyPhoneNumber];
}
@end
